package com.xjoyt.pay.master.dao.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.Predicate;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;

import com.xjoyt.pay.abstracts.AbstractDao;
import com.xjoyt.pay.dto.PageParam;
import com.xjoyt.pay.dto.PageResult;
import com.xjoyt.pay.master.dao.CheckoutRepositoryCustom;
import com.xjoyt.pay.master.params.CheckoutPageParam;
import com.xjoyt.pay.master.po.CompanyCheckout;
import com.xjoyt.pay.master.repository.CheckoutRepository;

public class CheckoutRepositoryImpl extends AbstractDao implements CheckoutRepositoryCustom {

	@Autowired
	private CheckoutRepository repository;

	@Override
	public PageResult<CompanyCheckout> loadPage(PageParam<CheckoutPageParam> param) {

		Pageable pageable = getPageable(param);
		Specification<CompanyCheckout> spec = getSpecification(param.query);
		Page<CompanyCheckout> pageResult = repository.findAll(spec, pageable);

		return new PageResult<CompanyCheckout>(pageResult.getTotalElements(), pageResult.getContent());
	}

	private Specification<CompanyCheckout> getSpecification(CheckoutPageParam param) {
		Specification<CompanyCheckout> spec = (root, query, cb) -> {
			List<Predicate> list = new ArrayList<>();
			// if (StringUtils.isNotBlank(param.parentId))
			// list.add(cb.or(cb.equal(root.get("order").get("merchant").get("company").get("id"),
			// param.parentId),
			// cb.like(root.get("order").get("merchant").get("company").get("path"),
			// "%" + param.parentId + "%")));
			if (StringUtils.isNotBlank(param.query)) {
				for (String string : param.query.split(" ")) {
					if (StringUtils.isBlank(string))
						continue;
					String like = "%" + string + "%";
					list.add(cb.or(cb.like(root.get("order").get("no"), like)));
				}
			}
			// if (param.success != null) {
			// if (param.success)
			// list.add(cb.equal(root.get("success"), param.success));
			// else
			// list.add(cb.or(cb.equal(root.get("success"), false),
			// cb.isNull(root.get("success"))));
			// }
			// if (param.type != null) {
			// list.add(cb.equal(root.get("type"), param.type));
			// // list.add(cb.or(cb.equal(root.get("type"), false),
			// // cb.isNull(root.get("type"))));
			// }
			if (CollectionUtils.isNotEmpty(list))
				query.where(cb.and(list.toArray(new Predicate[list.size()])));

			return null;
		};
		return spec;
	}
}
